package com.pinapel.aixml.controller.Menu;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import com.pinapel.aixml.controller.IMainController;
import com.pinapel.aixml.controller.IMenuController;
import com.pinapel.aixml.controller.MainController;
import com.pinapel.aixml.controller.Editor.AbstractTextEditorController;
import com.pinapel.aixml.models.EnumModelType;
import com.pinapel.aixml.models.Model;
import com.pinapel.aixml.models.xml.AbstractXMLModel;
import com.pinapel.aixml.tools.FileManager;
import com.pinapel.aixml.tools.i18n.I18n;
import com.pinapel.aixml.ui.actions.SaveFile;
import com.pinapel.aixml.ui.menuBar.MenuFile;

public class MenuFileController implements IMenuFileController {

	private MenuFile mView;
	private IMenuController mTopController;

	// Constructor
	public MenuFileController(IMenuController top) {
		mTopController = top;
	}

	// Methods
	@Override
	public void setTopController(IMenuController cont) {
		this.mTopController = cont;
	}

	@Override
	public MenuFile getView() {
		return mView;
	}

	@Override
	public void setView(MenuFile view) {
		this.mView = view;
		this.mView.setController(this);
	}

	@Override
	public void openFile(File f) {

		// Load the type of document
		EnumModelType typeOfDocument = FileManager.getTypeOfDocument(f);
		// Load the model
		AbstractXMLModel editorModel = getModel().get(typeOfDocument);
		// Load the controller
		AbstractTextEditorController editorController = getMainController().getEditorController().getController(typeOfDocument);
				
		/*
		 * Pregunto si deseo guardar en caso de:
		 * Si no existe el fichero y el texto no esta vacio
		 * o
		 * si el fichero existe y el texto ha cambiado
		 */
		if((editorModel.getFile()==null && !editorController.isEmptyText())
			||( !(editorModel.getFile()==null) && editorController.differentsText())){
//			&& editorController.getTextFromView().compareTo(editorModel.getText())!=0)){
			int optionSelected = JOptionPane.showConfirmDialog(null,
					I18n.getString(I18n.UI053_OPEN_DIALOG_BOX_TEXT),
					I18n.getString(I18n.UI028_OPEN),
					JOptionPane.YES_NO_CANCEL_OPTION);
			switch(optionSelected){
			case JOptionPane.CANCEL_OPTION:
				// Nothing happens, abort all process.
				return;
			case JOptionPane.YES_OPTION:
				// Save the text before overwrite it
				saveFile(editorController.getTextFromView(), typeOfDocument);
				break;
			case JOptionPane.NO_OPTION:
				break;
			}	
		}
		
		// Load the text in a String
		String theText = FileManager.loadFile(f);
		
		// Store the String and file descriptor into model
		editorModel.setText(theText);
		editorModel.setFile(f);
		
		// Set the view
		editorController.setText(theText);
		editorController.saved();
	}

	@Override
	public void saveFileAs(File f) {
		// Load the appropriate model
		AbstractXMLModel model = getModel().get(FileManager.getTypeOfDocument(f));
		// Load the Controller
		AbstractTextEditorController editorController = mTopController.getMainController().getEditorController().getController(FileManager.getTypeOfDocument(f));
		// Load the text
		String text = editorController.getTextFromView();
		
		model.setText(text);
		model.saveText(f);
		// Guardamos referencia en modelo a fichero abierto
		
		editorController.saved();
	}

	@Override
	public IMainController getMainController() {
		return mTopController.getMainController();
	}

	@Override
	public Model getModel() {
		return this.getMainController().getModel();
	}

	@Override
	public void newFile() {
		// Get the type of document of the current tab
		EnumModelType typeOfDocument = getMainController().getFocusedTab();
		// Get the controller for the current tab
		AbstractTextEditorController editorController = getMainController()
				.getEditorController().getController(typeOfDocument);
		// Get the model for this tab
		AbstractXMLModel editorModel = getModel().get(typeOfDocument);
		
		// Compare if the strings are equals
		int optionSelected = JOptionPane.NO_OPTION;
		boolean different = editorController.differentsText();
		
		// Shows a dialog to ask if the user want to lose unsaved text in this tab
		if (different) {
			optionSelected = JOptionPane.showConfirmDialog(null,
					I18n.getString(I18n.UI052_NEW_DIALOG_BOX_TEXT),
					I18n.getString(I18n.UI027_NEW), JOptionPane.YES_NO_OPTION);
		}
		
		/*
		 *  If the text is the same (no changes) and the user want delete the text
		 *  It will be deleted
		 */
		if (!different || optionSelected == JOptionPane.YES_OPTION) {
			editorController.setText("");
			editorController.needSave();
			mTopController.getMainController().cleanTreeView();
			editorModel.setFile(null);			
		}
	}

	@Override
	public void saveFile(String text, EnumModelType type) {
		File file;
		// Load the model
		AbstractXMLModel editorModel = getModel().get(type);
		
		if (editorModel.getFile()==null) {
			// If this model don't have a File descriptor try to create a new one.
			SaveFile saveFrame = new SaveFile();
			if(saveFrame.getOption() != JFileChooser.APPROVE_OPTION){
				return;
			}
			file = saveFrame.getSelectedFile();
		} else {
			// If a File descriptor exists it will load.
			file = editorModel.getFile();
		}
		
		if(file.exists()){
			// Ask for overwrite
			int optionSelected = JOptionPane.showConfirmDialog(null,
					I18n.getString(I18n.UI051_SAVEAS_DIALOG_BOX_TEXT),
					I18n.getString(I18n.UI029_SAVE), JOptionPane.YES_NO_OPTION);
			if(optionSelected == JOptionPane.NO_OPTION){
				// Don't want overwrite this file
				return;
			}
		}
		// Guardo el texto en la variable
		editorModel.setText(text);
		// Le dice al modelo que lo guarde
		editorModel.saveText(file);
			
		AbstractTextEditorController editorController = mTopController.getMainController().getEditorController().getController(type);
		editorController.saved();
			
		/*
		 * File could be a null pointer, it's happens when try but select a file,
		 * but the operation is canceled by user. In this case this operation will be
		 * aborted and no text is saved in a file descriptor.
		 * 
		 *  In a future implementation a exception could be throw.
		 */
	}
	
	/**
	 * This method ask for a valid file descriptor in case it doesn't exist
	 * previously, in case it already exist write the text storaged in the model in the file
	 * descriptor. 		
	 * @param model The model file to be saved
	 */
	@Deprecated
	private void saveBeforeOpen(AbstractXMLModel model, String text){
		File file;
		SaveFile saveDialog;
		// Nunca ha sido guardado
		if(model.getFile()==null){
			// SAVE AS
			saveDialog = new SaveFile();
			file = saveDialog.getSelectedFile();
		} else {
			file = model.getFile();
		}
		if(file != null){
			// SAVE
			model.setText(text);
			model.saveText(file);
		}
	}
	
	/**
	 * Overwrite the model with the text and the file descriptor. No ask are done.
	 * @param model to overwrite
	 * @param f the new file descriptor
	 */
	@Deprecated
	private void openOverwriting(AbstractXMLModel model, File f, EnumModelType type){
		// Load the text in a String
		String theText = FileManager.loadFile(f);
		
		
		// Store the String and file descriptor into model
		model.setText(theText);
		model.setFile(f);
		// Set the view
		AbstractTextEditorController editorController = mTopController.getMainController().getEditorController().getController(type);
		editorController.setText(theText);
		editorController.saved();
		
	}
}
